from fastapi import APIRouter, Depends
from fastapi.responses import JSONResponse
from qcloud_cos import CosS3Client
from src.dependencies.cos_client import get_cos_client, test_cos_connection
from src.config import settings

router = APIRouter()

@router.get("/health",
         summary="Health check endpoint",
         response_description="Health check status including COS connection and environment variables")
async def health_check(cos_client: CosS3Client = Depends(get_cos_client)):
    """
    健康检查端点，检查以下内容：
    1. COS 连接状态
    2. 环境变量配置
    3. 应用基本信息
    """
    health_status = {
        "status": "healthy",
        "components": {
            "cos": {
                "status": "healthy",
                "details": {}
            },
            "config": {
                "status": "healthy",
                "details": {}
            }
        }
    }

    # 检查 COS 连接
    cos_result = test_cos_connection()
    if cos_result["status"] == "error":
        health_status["components"]["cos"]["status"] = "unhealthy"
        health_status["components"]["cos"]["details"] = cos_result["details"]
        health_status["status"] = "unhealthy"
    else:
        health_status["components"]["cos"]["details"] = cos_result["details"]

    # 检查配置
    try:
        # 检查必要的环境变量是否存在
        required_vars = [
            "COS_REGION",
            "COS_SECRET_ID",
            "COS_SECRET_KEY",
            "COS_BUCKET_NAME",
            "COS_APP_ID"
        ]
        
        missing_vars = []
        for var in required_vars:
            if not getattr(settings, var, None):
                missing_vars.append(var)
        
        if missing_vars:
            health_status["components"]["config"]["status"] = "unhealthy"
            health_status["components"]["config"]["details"] = {
                "error": f"Missing required environment variables: {', '.join(missing_vars)}"
            }
            health_status["status"] = "unhealthy"
        else:
            health_status["components"]["config"]["details"] = {
                "app_name": settings.APP_NAME,
                "debug": settings.DEBUG,
                "cos_region": settings.COS_REGION,
                "cos_bucket_name": settings.COS_BUCKET_NAME,
                "cos_app_id": settings.COS_APP_ID
            }
    except Exception as e:
        health_status["components"]["config"]["status"] = "unhealthy"
        health_status["components"]["config"]["details"] = {
            "error": f"Configuration error: {str(e)}"
        }
        health_status["status"] = "unhealthy"

    return JSONResponse(
        status_code=200 if health_status["status"] == "healthy" else 503,
        content=health_status
    ) 